package io.flash.rpc.client;

import io.flash.rpc.protocol.PacketCodec;
import io.flash.rpc.protocol.RpcRequestPacket;
import io.flash.rpc.protocol.RpcResponsePacket;
import io.flash.rpc.protocol.RpcResponsePacketHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {

    private Channel channel;

    public void send(RpcRequestPacket rpcRequestPacket) {
        channel.writeAndFlush(rpcRequestPacket);
    }

    public void start() {
        channel = new Bootstrap().group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();

                        pipeline.addLast(new PacketCodec());
                        pipeline.addLast(new RpcResponsePacketHandler());

                    }
                })
                .connect("127.0.0.1", 8000)
                .awaitUninterruptibly()
                .channel();
    }
}
